<?php

namespace app\common\model;

use app\common\model\BaseModel as BaseModel;
use app\common\traits\TimeCacheTrait;
use ShidianUtil\Utils\CheckUtil;

/**
 * Class Member
 * @package app\model
 * @property int $id
 * @property string $sid
 * @property int $status
 * @property int $checkStatus
 * @property int $type
 * @property int $subType
 * @property string $phone
 * @property string $origin
 * @property string $qCellCoreProvince
 * @property string $qCellCoreCity
 * @property int $modPhoneTime
 * @property string $passwd
 * @property string $salt
 * @property string $unionid
 * @property string $openidWeiXin
 * @property string $openidWechat
 * @property string $openidWechatOpen
 * @property string $unionidBaidu
 * @property string $openidBaidu
 * @property string $unionidDouyin
 * @property string $openidDouyin
 * @property int $followedWechat
 * @property string $nickname
 * @property string $realname
 * @property string $headImgUrl
 * @property string $cropImgUrl
 * @property int $wanzhengNicheng
 * @property int $wanzhengTouxiang
 * @property int $channel
 * @property int $provinceId
 * @property int $cityId
 * @property int $gender
 * @property int $isSettled
 * @property int $settledTime
 * @property int $muted
 * @property int $mutedLength
 * @property int $mutedTime
 * @property string $mutedCause
 * @property int $mutedUserId
 * @property int $mutedActionTime
 * @property int $disabledUserId
 * @property int $disabledActionTime
 * @property int $matchStatus
 * @property int $isInviter
 * @property int $inviterTime
 * @property string $inviteCode
 * @property string $axbPhone
 * @property int $companyId
 * @property int $userPersonnelId
 * @property int $svip
 * @property int $updated
 * @property int $created
 * @property string $headImg
 * @property string $headImgThumb
 * @property string $channelStr
 * @property string $not_free_ask_sum
 * @property string $showName
 * @property MemberInfo $memberInfo
 * @property Account $account
 * @property Account $card
 * @property Account $coin
 * @property User $mutedUser
 * @property User $disabledUser
 * @method $this shield() 屏蔽前端不需要的信息
 * @method $this shortMember() 简短的用户信息
 * @method $this shortLawyer() 简短的律师信息
 * @method $this memberBasicInfo() 基础的用户&律师信息
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037579
 * @link https://www.kancloud.cn/manual/think-orm/1257998
 * @link https://www.kancloud.cn/thinkphp/master-database-and-model/265551
 */
class Member extends BaseModel implements MessageSenderInterface
{
    use TimeCacheTrait;

    // 全部第三方登录的身份唯一标志
    const UNIONID_ARR = [
        'unionid', 'openidWeiXin', 'openidWechat', 'openidWechatOpen', 'followedWechat',
        'unionidBaidu', 'openidBaidu',
        'unionidDouyin', 'openidDouyin',
    ];

    protected $name = 'Member';

    public static function signVerifierHash(string $password, string $salt)
    {
        return md5(md5($password) . $salt);
    }

    // SVIP的省份
    public function svipProvinces()
    {
        return $this->belongsToMany(Area::class, 'member_svip_province_rel', 'provinceId', 'memberId');
    }

    public function province()
    {
        return $this->hasOne(Area::class, 'id', 'provinceId');
    }

    public function city()
    {
        return $this->hasOne(Area::class, 'id', 'cityId');
    }

    /**
     * 免费提问
     * @return \think\model\relation\HasMany
     */
    public function freeAsk()
    {
        return $this->hasMany(Consulting::class, 'memberId', 'id');
    }

    /**
     * 不免费的提问
     * @return \think\model\relation\HasMany
     */
    public function notFreeAsk()
    {
        return $this->hasMany(Consulting::class, 'memberId', 'id');
    }

    /**
     * 免费提问
     * @return \think\model\relation\HasMany
     */
    public function lawyerFreeAsk()
    {
        return $this->hasMany(Consulting::class, 'lawyerId', 'id');
    }

    /**
     * 不免费的提问
     * @return \think\model\relation\HasMany
     */
    public function lawyerNotFreeAsk()
    {
        return $this->hasMany(Consulting::class, 'lawyerId', 'id');
    }

    /**
     * 成为SVIP后的单子
     * @return \think\model\relation\HasMany
     */
    public function lawyerSvipAsk()
    {
        return $this->hasMany(Consulting::class, 'lawyerId', 'id');
    }

    /**
     * 用户-该用户的订单
     * @return \think\model\relation\HasMany
     */
    public function trades()
    {
        return $this->hasMany(Trade::class, 'memberId', 'id');
    }

    /**
     * 余额充值订单
     * @return \think\model\relation\MorphMany
     */
    public function accountRechargeTrades()
    {
        return $this->morphMany(Trade::class, ['tradeType', 'memberId'], TRADE_BALANCE_RECHARGE);
    }

    /**
     * 代币充值订单
     * @return \think\model\relation\MorphMany
     */
    public function tokenRechargeTrades()
    {
        return $this->morphMany(Trade::class, ['tradeType', 'memberId'], TRADE_TOKEN_RECHARGE);
    }

    /**
     * 用户-该用户的已分账的订单
     * @return \think\model\relation\HasMany
     */
    public function settledTrades()
    {
        return $this->hasMany(Trade::class, 'memberId', 'id');
    }

    /**
     * 律师-今日咨询
     * @return \think\model\relation\HasMany
     */
    public function lawyerTodayConsulting()
    {
        return $this->hasMany(Consulting::class, 'lawyerId', 'id');
    }

    /**
     * 律师-待处理咨询
     * @return \think\model\relation\HasMany
     */
    public function pendingConsulting()
    {
        return $this->hasMany(Consulting::class, 'lawyerId', 'id');
    }

    /**
     * 律师-今日案源
     * @return \think\model\relation\BelongsToMany
     */
    public function lawyerTodayLawCases()
    {
        return $this->belongsToMany(LawCase::class, 'trade', 'lawCaseId', 'memberId');
    }

    /**
     * 律师-今日收入
     * @return \think\model\relation\HasMany
     */
    public function transfer()
    {
        return $this->hasMany(Transfer::class, 'memberId', 'id');
    }

    /**
     * 律师信息
     * @return \think\model\relation\HasOne
     */
    public function memberInfo()
    {
        return $this->hasOne(MemberInfo::class, 'memberId', 'id');
    }

    /**
     * SVIP保证金
     * @return \think\model\relation\morphOne
     */
    public function margin()
    {
        return $this->morphOne(Account::class, ['payMethod', 'memberId'], PAYMENT_MARGIN);
    }

    /**
     * 余额账户
     * @return \think\model\relation\morphOne
     */
    public function account()
    {
        return $this->morphOne(Account::class, ['payMethod', 'memberId'], PAYMENT_ACCOUNT);
    }

    /**
     * 获客卡账户
     * @return \think\model\relation\morphOne
     */
    public function card()
    {
        return $this->morphOne(Account::class, ['payMethod', 'memberId'], PAYMENT_CARD);
    }

    /**
     * 通信币账户
     * @return \think\model\relation\morphOne
     */
    public function coin()
    {
        return $this->morphOne(Account::class, ['payMethod', 'memberId'], PAYMENT_COIN);
    }

    // 该用户邀请的用户
    public function inviteMembers()
    {
        return $this->belongsToMany(Member::class, 'member_invite', 'memberIdInvite', 'memberId');
    }

    // 邀请该用户的用户
    public function inviteMember()
    {
        return $this->hasOneThrough(Member::class, MemberInvite::class, 'memberIdInvite', 'id', 'id', 'memberId');
    }

    // 禁言该用户的管理员
    public function mutedUser()
    {
        return $this->belongsTo(User::class, 'mutedUserId', 'id');
    }

    // 禁用该用户的管理员
    public function disabledUser()
    {
        return $this->belongsTo(User::class, 'disabledUserId', 'id');
    }

    /**
     * 多对多
     * @return \think\model\relation\BelongsToMany
     */
    public function ignoreConsulting()
    {
        return $this->belongsToMany(Consulting::class, 'consulting_ignore', 'consultingId', 'lawyerId');
    }

    /**
     * 注册来源的链头
     * @return \think\model\relation\BelongsTo
     */
    public function fromChain()
    {
        return $this->belongsTo(Chain::class, 'chain', 'chain');
    }

    // 获取
    public function getMemberPtAttr($value, $data)
    {
        $type = $data['type'] ?? null;
        $userPersonnelId = $data['userPersonnelId'] ?? null;
        $isSettled = $data['isSettled'] ?? null;

        if ($type == 1) {
            return '1';
        }

        if (is_id($userPersonnelId)) {
            return '1';
        }

        // 审核中律师
        if (is_numeric($isSettled) && $isSettled > 0) {
            return '1';
        }

        return '0';
    }

    // AXB通话号码
    public function getAxbPhoneAttr($value, $data)
    {
        if (not_blank($value) && CheckUtil::isPhoneNumber($value)) {
            return $value;
        }
        return $data['phone'] ?? '';
    }

    public function getAxbPhoneShowStrAttr($value, $data)
    {
        $phone = $this->getAxbPhoneAttr($data['axbPhone'] ?? '', $data);
        if (is_blank($phone) || !CheckUtil::isPhoneNumber($phone)) {
            return '';
        }

        return substr_replace($phone, '_****_', 3, 4);
    }

    public function getShowNameAttr($value, $data)
    {
        return $data['type'] == 1 ? $data['realname'] : $data['nickname'];
    }

    public function getNotFreeAskSumAttr($value, $data)
    {
        return $value ?: '0';
    }

    // 用户头像
    public function getHeadImgAttr($value, $data)
    {
        $headImgUrl = $data['headImgUrl'] ?? null;
        if (is_blank($headImgUrl)) {
            $headImgUrl = '/storage/static/images/member/touxiang.png';
        }
        return image_url($headImgUrl);
    }

    // 用户头像缩略图
    public function getHeadImgThumbAttr($value, $data)
    {
        $headImgUrl = $data['headImgUrl'] ?? null;
        if (is_blank($headImgUrl)) {
            $headImgUrl = '/storage/static/images/member/touxiang.png';
        }
        return image_url($headImgUrl, 'thumb');
    }

    // 裁剪后头像
    public function getCropImgAttr($value, $data)
    {
        return image_url($data['cropImgUrl'] ?? '');
    }

    // 是否是已绑定的员工
    public function getIsPersonnelAttr($value, $data)
    {
        return is_id($data['userPersonnelId'] ?? null) ? '1' : '0';
    }

    // 省份ID数组
    public function getSvipProvincesIdsAttr($value, $data)
    {
        return $this->svipProvinces->column('id');
    }


    /**
     * 简短的用户信息
     * @param $query
     * @return void
     */
    public function scopeMemberBasicInfo($query)
    {
        $field = ['id', 'nickname', 'realname', 'headImgUrl', 'cropImgUrl', 'type'];
        $append = ['headImg', 'headImgThumb', 'cropImg', 'showName'];
        $hidden = ['headImgUrl'];

        $query->tableField($field, $this->getTable())
              ->append($append)
              ->hidden($hidden);
    }

    /**
     * 简短的用户信息
     * @param $query
     * @return void
     */
    public function scopeShortMember($query)
    {
        $field = ['id', 'nickname', 'realname', 'headImgUrl', 'cropImgUrl', 'phone', 'type'];
        $append = ['headImg', 'headImgThumb', 'cropImg', 'showName'];
        $hidden = ['headImgUrl'];

        $query->tableField($field, $this->getTable())
              ->append($append)
              ->hidden($hidden);
    }

    /**
     * 简短的律师信息
     * @param $query
     * @return void
     */
    public function scopeShortLawyer($query)
    {
        $field = ['id', 'nickname', 'realname', 'headImgUrl', 'cropImgUrl', 'phone', 'type', 'svip'];
        $append = ['headImg', 'headImgThumb', 'cropImg', 'showName'];
        $hidden = ['headImgUrl'];

        $query->tableField($field, $this->getTable())
              ->append($append)
              ->hidden($hidden);
    }

    /**
     * 消息发送者
     * @param Member $query
     */
    public function scopeSender($query)
    {
        $query->tableField(['id', 'nickname', 'realname', 'headImgUrl', 'cropImgUrl', 'type'], $this->getTable())
              ->append(['showName', 'headImg', 'headImgThumb', 'cropImg'])
              ->hidden(['headImgUrl']);
    }

    /**
     * 屏蔽前端不需要的信息
     * @param Member $query
     */
    public function scopeShield($query)
    {
        $query->hidden(['headImgUrl', 'passwd', 'salt', 'unionid', 'openidWeiXin', 'openidWechat', 'openidWechatOpen', 'unionidBaidu', 'openidBaidu', 'unionidDouyin', 'openidDouyin'], true);
    }

    /**
     * 1对1
     * @return \think\model\relation\HasOne
     */
    //    public function one(){
    //        return $this->hasOne( Test1::class, 'Test1表中的键', 'Member表中的键');
    //    }

    /**
     * 1对多
     * @return \think\model\relation\HasMany
     */
    //    public function many(){
    //        return $this->hasMany( Test1::class, 'Test1表中的键', 'Member表中的键');
    //    }

    /**
     * 多对多
     * @return \think\model\relation\BelongsToMany
     */
    //    public function belongs(){
    //        return $this->belongsToMany( Test1::class, '中间表', '中间表中Test1的键', '中间表中Member的键');
    //    }
}
